package com.zb.validation;

import com.zb.annotation.NumberLengthPattern;
import com.zb.annotation.NumberPattern;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.Objects;
import java.util.regex.Pattern;

/**
 * @Author WEN
 * @Date 2023/8/2 0002
 **/
public class NumberLengthValidator implements ConstraintValidator<NumberLengthPattern, Number> {
    private int max;
    private int min;

    @Override
    public void initialize(NumberLengthPattern constraintAnnotation) {
        // 赋值给全局变量
        this.max = constraintAnnotation.max();
        this.min = constraintAnnotation.min();
    }

    @Override
    public boolean isValid(Number val, ConstraintValidatorContext constraintValidatorContext) {
        // 数据为空则放行
        if (Objects.isNull(val)) {
            return true;
        }
        if (this.min > 0 && val.toString().length() < this.min) {
            return false;
        }
        if (val.toString().length() > this.max) {
            return false;
        }
        // 默认放行
        return true;
    }


}
